<template>
    <div>
        <div class="e-form" v-if="dialogVisible === false">
            <div class="tabs">
                <div class="tabs-title">基本信息</div>
                <div style="width: 100%" class="form">
                    <el-form :model="formData" label-width="170px" :rules="rules" ref="ruleForm">
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="拟招标项目名称" width="200" prop="tenderName">
                                    <el-input v-model="formData.tenderName"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="租赁人" width="230" prop="tenderUser">
                                    <ComInputSelectUnit
                                        :orgName.sync="formData.tenderUser"
                                        :orgId.sync="formData.tenderUserId"
                                        :SelectedIDs="
                                            formData.tenderUserId !== ''
                                                ? [formData.tenderUserId]
                                                : []
                                        "
                                        type="getParentOrg"
                                    />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="招标方式" prop="tenderForm">
                                    <el-select
                                        v-model="formData.tenderForm"
                                        placeholder="请选择"
                                        @change="selectChange($event, '租赁方式')"
                                    >
                                        <el-option
                                            v-for="item in options.tenderForm"
                                            :key="item.value"
                                            :label="item.label"
                                            :value="item.value"
                                        >
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="申请日期" prop="applyTime">
                                    <el-date-picker
                                        v-model="formData.applyTime"
                                        type="date"
                                        placeholder="选择日期"
                                        :clearable="false"
                                        value-format="yyyy-MM-dd"
                                    >
                                    </el-date-picker>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <!-- 需要id和name -->
                                <el-form-item label="申请单位" width="230" prop="applyOrgName">
                                    <ComInputSelectUnit
                                        :orgName.sync="formData.applyOrgName"
                                        :orgId.sync="formData.applyOrgId"
                                        :SelectedIDs="
                                            formData.applyOrgId !== '' ? [formData.applyOrgId] : []
                                        "
                                    />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item
                                    label="拟租赁金额（元）"
                                    width="200"
                                    prop="tenderAmount"
                                >
                                    <span>{{ formData.tenderAmount }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="投标保证金（元）" prop="tenderBail">
                                    <el-input
                                        v-model="formData.tenderBail"
                                        v-enterJustFloat
                                        @blur="inputblur(formData, 'tenderBail')"
                                    ></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item
                                    label="租赁公告"
                                    prop="tenderNotice"
                                    v-if="
                                        formData.tenderForm !== '2' && formData.tenderForm !== '4'
                                    "
                                >
                                    <el-button
                                        style="width: 222px"
                                        class="btn-greenYellow"
                                        @click="handleNotice"
                                        >招标公告</el-button
                                    >
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="录入机构" prop="orgName">
                                    <span>{{ formData.orgName }}</span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="状态">
                                    <span>草稿</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="租赁类型" prop="leaseType">
                                    <span>{{ formData.leaseType | leaseType(this) }}</span>
                                    <!-- <el-select v-model="formData.leaseType" placeholder="请选择">
                                        <el-option
                                            v-for="(item, index) in options.leaseType"
                                            :key="index + 1"
                                            :label="item"
                                            :value="index + 1"
                                        >
                                        </el-option>
                                    </el-select> -->
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="币种" prop="currencyId">
                                    <el-select
                                        v-model="formData.currencyId"
                                        placeholder="请选择"
                                        @change="selectChange($event, '币种')"
                                    >
                                        <el-option
                                            v-for="item in options.currency"
                                            :key="item.kvValue"
                                            :label="item.kvKey"
                                            :value="item.kvValue"
                                        >
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <!-- <el-row>
                            <el-col :span="12">
                                <el-form-item label="税额" width="200" prop="tenderAmount">
                                    <span>{{ formData.taxAmount }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row> -->
                        <el-row>
                            <el-form-item label="租赁需求陈述" prop="purchaseDemandStatement">
                                <el-input
                                    type="textarea"
                                    :rows="2"
                                    placeholder="请输入内容"
                                    v-model="formData.purchaseDemandStatement"
                                    style="margin-right: 110px"
                                >
                                </el-input>
                            </el-form-item>
                        </el-row>
                        <el-row>
                            <el-form-item label="备注">
                                <el-input
                                    type="textarea"
                                    :rows="2"
                                    placeholder="请输入内容"
                                    v-model="formData.remarks"
                                    style="margin-right: 110px"
                                >
                                </el-input>
                            </el-form-item>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="本位币" prop="baseCurName">
                                    <!-- 传id和名称 -->
                                    <span>{{ formData.baseCurName }}</span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12" v-if="formData.baseCurName !== formData.currency">
                                <el-form-item label="人民币汇率" prop="rmbRate">
                                    <span>{{ formData.rmbRate }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12" v-if="formData.releaseState === 1">
                                <el-form-item label="发布时间：">
                                    <!-- 传id和名称 -->
                                    <span>{{ formData.relaseTime }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
            </div>
            <div class="buttons">
                <el-button type="primary" class="btn-blue" @click="submit">保存</el-button>
                <el-button @click="handleClose">取消</el-button>
            </div>
        </div>
        <!-- dialog -->
        <ComNoticeDialog
            ref="ComNoticeDialog"
            :dialogVisible.sync="dialogVisible"
            :tenderClass="parseInt(formData.tenderClass)"
            :tenderForm="String(formData.tenderForm)"
            v-if="Object.keys(formData).length !== 0"
            :content="formData.tenderNotice"
            @save="noticeSave"
        />
    </div>
</template>

<script>
// import ComTreeTable from '@/templates/table/treeTable.vue'
// import ComTreeFile from '@/templates/table/treeFile.vue'
// import ComPagination from '@/components/pagination/pagination.vue'
// import applyRequest from '@/api/tender/apply.js'
import equipmentLeasingRequest from '@/api/tender/equipmentLeasing.js'
import authRequest from '@/api/identity/auth.js'
import ComNoticeDialog from '@/components/common/noticeDialog.vue'
import ComInputSelectUnit from '@/pages/bidding/common/inputSelectUnit.vue'
import { mapState } from 'vuex'

export default {
    data () {
        const not0RmbRate = (rule, value, callback) => {
            if (typeof value === 'number' && value === 0) {
                return callback(new Error('人民币汇率不能为0'))
            } else {
                callback()
            }
        }
        const greaterZero = (rule, value, callback) => {
            if (typeof value === 'number' && value < 0) {
                return callback(new Error('不能为负数'))
            } else {
                callback()
            }
        }
        return {
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: ''
            },
            tableData: [],
            value: '',
            textarea: '',
            // 招标类别 0工程施工招标 1其他工程招标 2物资供应招标 3物资供应加工 4周材租赁招标 5 服务采购招标 6机材收入招标 7设备采购招标 8设备租赁招标 9 其他机料采购招标
            // 招标状态 0，新增 1申请中 2已申请 3已发布 4 补遗中 5评标登记中 6已评标 7已公示 8关闭中 9已关闭
            formData: {
                applyOrgId: '',
                applyOrgName: '',
                applyTime: '',
                baseCurAmount: 0,
                baseCurId: '',
                baseCurName: '',
                baseCurRate: 0,
                baseCurTenderAmount: 0,
                currency: '',
                currencyId: '',
                leaseType: 1,
                purchaseDemandStatement: '',
                remarks: '',
                rmbRate: 0,
                tenderAmount: 0,
                tenderBail: 0,
                tenderEndTime: '',
                tenderFee: 0,
                tenderForm: '',
                tenderName: '',
                tenderNotice: '',
                tenderUser: '',
                tenderUserId: '',
                tenderClass: 8 // 用于获取公告，不传要报错
            },
            // selectData: [],
            // selectDataClone: [],
            selectTableColumnAttr: [
                {
                    label: '机构Id',
                    prop: 'orgId'
                },
                {
                    label: '机构名称',
                    prop: 'orgName'
                }
            ],
            selectTableColumnWidth: {
                leftWidth: '150',
                rightWidth: '100'
            },
            dialogVisible: false,
            rules: {
                billNo: { required: true, message: '请输入招标编号', trigger: 'blur' },
                tenderName: { required: true, message: '请输入拟招标项目名称', trigger: 'blur' },
                tenderForm: { required: true, message: '请选择招标方式', trigger: 'change' },
                tenderType: { required: true, message: '请选择招标类型', trigger: 'change' },
                projectName: { required: true, message: '请输入项目名称', trigger: 'blur' },
                tenderNotice: { required: true, message: '请输入公告', trigger: 'change' },
                tenderBail: [
                    { required: true, message: '请输入投标保证金（元）', trigger: 'blur' },
                    // { type: 'number', message: '保证金必须为数字值' },
                    { validator: greaterZero, trigger: 'blur' }
                ],
                currencyId: { required: true, message: '请选择币种', trigger: 'change' },
                tenderAmount: {
                    required: true,
                    message: '请输入拟招标金额（元）',
                    trigger: 'blur'
                },
                taxAmount: { required: true, message: '请输入税额', trigger: 'blur' },
                applyTime: { required: true, message: '请选择申请日期', trigger: 'change' },
                tenderState: { required: true, message: '请输入招标状态', trigger: 'blur' },
                state: { required: true, message: '请输入申请状态', trigger: 'blur' },
                applyOrgName: { required: true, message: '请选择申请单位', trigger: 'change' },
                projectOverview: {
                    required: true,
                    message: '请输入招标项目工程概况',
                    trigger: 'blur'
                },
                remarks: [
                    // { required: true, message: '请输入备注', trigger: 'blur' },
                    { max: 500, message: '最多允许输500个汉字', trigger: 'blur' }
                ],
                orgName: { required: true, message: '请输入录入机构', trigger: 'blur' },
                tenderUser: { required: true, message: '请选择招标单位', trigger: 'change' },
                baseCurName: { required: true, message: '没有设置本位币，请联系集团信息化管理员设置！', trigger: 'blur' },
                rmbRate: [
                    { required: true, message: '请选择币种', trigger: 'change' },
                    { validator: not0RmbRate, trigger: 'change' }
                ],
                centralizedPurchasingState: {
                    required: true,
                    message: '请选择集中采购',
                    trigger: 'change'
                },
                tenderFee: [
                    { required: true, message: '请输入购买标书费用', trigger: 'blur' },
                    { type: 'number', message: '购买标书费用必须为数字值' },
                    { validator: greaterZero, trigger: 'blur' }
                ],
                tenderEndTime: { required: true, message: '请选择投标截止时间', trigger: 'change' },
                pushPurchasePlatformState: {
                    required: true,
                    message: '请选择发布到招采平台',
                    trigger: 'change'
                },
                purchaseDemandStatement: {
                    required: true,
                    message: '请输入采购需求陈述',
                    trigger: 'blur'
                },
                leaseType: {
                    required: true,
                    message: '请选择租赁类型',
                    trigger: 'change'
                },
            },
            windowHeight: null
            // selectDataPagination: {}
        }
    },
    computed: {
        ...mapState({
            options: state => state.biddingApplication.dictionaries,
            userInfo: state => state.userInfo
        })
    },
    components: {
        // ComTreeTable,
        // ComTreeFile,
        // ComPagination
        ComNoticeDialog,
        ComInputSelectUnit
    },
    created () {
        this.getVuexData()
        this.getNowDate()
        this.formData.baseCurName = this.userInfo.baseCyByOrgId.currencyName // 本位币名字
        this.formData.baseCurId = this.userInfo.baseCyByOrgId.currency // 本位币i
    },
    mounted () {},
    beforeDestroy () {
        this.$notify.closeAll()
    },
    methods: {
        inputblur (row, val) {
            row[val] = isNaN(parseFloat(row[val])) ? 0 : parseFloat(row[val])
        },
        noticeSave (content) {
            this.formData.tenderNotice = content
        },
        handleNotice () {
            if (this.formData.tenderForm === 2 || this.formData.tenderForm === 4) return
            this.dialogVisible = true
        },
        showBidding () {
            if (!this.tenderId) return // 前期需求可切换，现在不需要
            this.$notify.closeAll()
            this.$notify({
                title: '查看招标详情',
                dangerouslyUseHTMLString: true,
                message: `正式环境：客户端打开新页面<br>
                测试环境：手动打开新页面<br>
                <textarea cols="35" rows="10">http://localhost:8080/biddingApplicationShow?tenderId=${this.tenderId}</textarea>
                `,
                duration: 0
            })
            // this.$router.push({
            //     path: './biddingApplicationShow',
            //     query: { tenderId: this.tenderId }
            // })
        },
        selectChange (kvId, label) {
            if (label === '采购方式') {
                this.options.tenderForm.forEach(item => {
                    if (kvId === item.value) {
                        this.formData.tenderFormName = item.label
                    }
                })
            } else if (label === '币种') {
                let index
                this.options.currency.forEach((item, key) => {
                    if (item.kvValue === kvId) {
                        index = key
                        this.formData.currency = item.kvKey
                    }
                })
                authRequest
                    .getRmbRate({
                        currency: index,
                        orgId: this.userInfo.orgInfo.orgId
                    })
                    .then(res => {
                        this.formData.rmbRate = res.rate
                        this.formData.rmbAmount = this.formData.tenderAmount * res.rate
                    })
                    .catch(() => {
                        this.formData.rmbRate = 0
                    })
            } else if (label === '目标预算') {
                ;('等待接口')
            }
        },
        openNewPage (name) {
            this.$notify.closeAll()
            if (name === 'OrgSelectData') {
                const params = JSON.stringify({
                    // 正式环境应该不用转换
                    title: '申请机构',
                    url: '/hr/org/getChildrenOrg',
                    method: 'get',
                    params: { orgId: this.$store.state.userInfo.orgInfo.orgId },
                    tableColumnAttr: this.selectTableColumnAttr,
                    tableColumnWidth: this.selectTableColumnWidth,
                    ifPagination: 0
                })
                this.$notify({
                    title: '申请机构',
                    dangerouslyUseHTMLString: true,
                    message: `正式环境：客户端打开新页面<br>
                测试环境：手动打开新页面<br>
                <textarea cols="35" rows="10">http://localhost:8080/selectData?params=${params}</textarea>
                <br><br>
                回调参数：<br>
                <textarea cols="35" rows="3" id="callBackData"></textarea><br>
                <button id="getPopData">执行回调方法</button>
                `,
                    duration: 0
                })
                document.querySelector('#getPopData').addEventListener('click', this.getPopData)
            }
        },
        getPopData () {
            const callBackData = JSON.parse(document.querySelector('#callBackData').value)
            this.formData.applyOrgId = callBackData.orgId
            this.formData.applyOrgName = callBackData.orgName
        },
        noFocus () {
            this.$refs.noFocus.blur()
        },
        submit () {
            this.$refs.ruleForm.validate(valid => {
                if (valid) {
                    equipmentLeasingRequest.applyCreate(this.formData).then(res => {
                        const callBack = () => {
                            this.$router.push({
                                path: './equipHireBiddingApplicationEdit',
                                query: { billid: res }
                            })
                        }
                        const cancelCallBack = () => {
                            this.$router.push('./equipHireBiddingApplication')
                        }
                        this.clientPop(
                            'suc',
                            '保存成功，是否继续？',
                            callBack,
                            null,
                            cancelCallBack
                        )
                    })
                } else {
                    return false
                }
            })
        },
        getVuexData () {
            // // 获取保存在vuex的数据
            // this.formData = {
            //     ...this.formData,
            //     ...JSON.parse(
            //         JSON.stringify(
            //             this.$store.state.biddingApplication.formData
            //         )
            //     )
            // }
            // 获取保存在vuex的常量
            if (Object.keys(this.$store.state.userInfo.orgInfo).length !== 0) {
                // 录入机构
                this.formData.orgId = this.$store.state.userInfo.orgInfo.orgId
                this.formData.orgName = this.$store.state.userInfo.orgInfo.orgName
                // 申请单位默认为录入机构
                this.formData.applyOrgId = this.$store.state.userInfo.orgInfo.orgId
                this.formData.applyOrgName = this.$store.state.userInfo.orgInfo.orgName
                // 招标单位默认为录入机构
                this.formData.tenderUserId = this.$store.state.userInfo.orgInfo.orgId
                this.formData.tenderUser = this.$store.state.userInfo.orgInfo.orgName
            }
            // console.log('this.formData1', this.formData)
        },
        getNowDate () {
            // 个位数前补0
            const zeroFill = function (num) {
                if (parseInt(num) < 10) {
                    num = '0' + num
                }
                return num
            }
            let nowtime = new Date()
            nowtime =
                zeroFill(nowtime.getFullYear()) +
                '-' +
                zeroFill(nowtime.getMonth() + 1) +
                '-' +
                zeroFill(nowtime.getDate())
            this.$set(this.formData, 'applyTime', nowtime)
        },
        handleClose () {
            this.$router.push('./equipHireBiddingApplication')
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        cellMouseEnter (row) {
            this.MouseEnterId = row.id
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        }
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}

.e-form {
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}

// .form {
//     // margin-top: 10px;
// }

.e-table {
    background: #fff;

    /* .top {
    .left {
      padding: 20px;
      padding-top: 0px;
    }
  } */
}

.upload {
    margin: 20px auto;
    display: flex;
    justify-content: center;
    text-align: center;
}

.upload-demo {
    display: flex;
    justify-content: center;
    align-items: center;
}

.el-tab-pane {
    margin-left: -10px;
}
</style>
